<template>
  <div class="app-container">
    <el-form ref="form" :model="form" label-width="80px" label-position="left" :rules="rules">
      <div class="examineTitle mb20">
        补卡申请
      </div>
      <p class="add-card-line" v-if="dayIndex">
        周{{ weekName[dayWeek] }}({{ dayIndex.time }}) 缺卡
      </p>
      <el-form-item label="补卡时间" prop="isEmpty">
        <el-row>
          <el-col :span="5">
            <el-date-picker type="date" placeholder="选择日期" v-model="dayData" style="width: 100%;" format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd" @change="dayDatafn()"></el-date-picker>
          </el-col>
          <el-col class="line" :span="1">-</el-col>
          <el-col :span="4">
            <el-time-picker placeholder="选择时间" v-model="timeData" style="width: 100%;" format="HH:mm"
                            value-format="HH:mm"></el-time-picker>
          </el-col>
          <el-col :span="24" v-if="erroStatus">
            <div class="not-error-line">
              当前时间，没有考勤异常无需补卡
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="补卡理由" prop="content">
        <el-input type="textarea" v-model="form.content" placeholder="补卡理由"></el-input>
      </el-form-item>
      <el-form-item label="图片" class="my-dialog">
        <image-upload v-model="form.file" :limit="9" :isShowTip="false"/>
      </el-form-item>
    </el-form>
    <el-dialog title="请选择补卡班次" :visible.sync="open" width="500px" append-to-body class="my-dialog">
      <div class="card-list">
        <p v-for="item in errorWorkList" @click="getDayLine(item)">周{{ weekName[dayWeek] }} ({{ item.time }})缺卡</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {cardReplacementAdd, signlistUserDay} from "@/api/system/leave"
import {mapGetters} from 'vuex'

export default {
  name: "index",
  components: {},
  props: ['flowData', 'deptOptions', 'workDay', 'workType'],
  data() {
    return {
      activeName: 'first',
      form: {
        userId: 0, // 用户id
        signTime: 0, // 补卡时间
        content: '', // 补卡原因
        file: '', // 文件地址
        flowId: 0, // 审核流程id
        isEmpty: '1'
      },
      rules: {
        content: [
          {required: true, message: '填写补卡理由', trigger: 'blur'},
        ],
        isEmpty: [
          {required: true, message: '填写补卡时间不能为空', trigger: 'blur'},
        ],
      },
      dayData: '',
      timeData: '',
      workOption: null, // 排班具体信息
      erroStatus: false,
      open: false,
      errorWorkList: [],
      dayWeek: 0,
      weekName: ['日', '一', '二', '三', '四', '五', '六'],
      dayIndex: null, // 补卡信息
      flagLoading: false
    }
  },
  computed: {
    ...mapGetters([
      'deptId',
      'userId'
    ]),
  },
  watch: {},
  created() {
  },
  methods: {
    cancel() {
      this.open = false
    },
    getDayLine(item) {
      if(!this.timeData){
        this.timeData = item.time.split(' ')[1]
      }
      this.dayIndex = this.$deepCopy(item)
      this.cancel()
    },
    dayDatafn() {
      console.log('查询当天是否有异常卡', this.dayData)
      console.log('排班类型', this.workType, this.workDay)
      if (this.dayData) {
        let day_ = this.dayData.split('-')
        // type 1 固定班制 2 排班制 0 未知
        if (this.workType == 1) {
          let firstDayOfMonth = new Date(this.dayData)
          let dayWeek = firstDayOfMonth.getDay() //0表示周日，1表示周一...6表示周六
          console.log('补卡那天星期几：', dayWeek)
          this.dayWeek = dayWeek
          this.workOption = this.workDay[dayWeek ? dayWeek - 1 : 6]
          if (this.workOption) {
            let start_Time = new Date().getTime() // 开始时间时间戳
            let end_Time = new Date(`${this.dayData} ${this.startTimeSon}`).getTime() // 开始时间时间戳
            if(end_Time>start_Time){
              this.$alert('当前时间，没有考勤异常无需补卡', '提示', {
                confirmButtonText: '确定',
                callback: action => {
                }
              });
              return
            }
            signlistUserDay({day: day_.join(''), userId: this.userId}).then(res => {
              let errorWorkList = []
              for (let item of res.data) {
                let checkTime_s = new Date(item.time).getTime() // 需要打卡时间
                let new_ = new Date().getTime()
                if (checkTime_s < new_) {
                  errorWorkList.push(item)
                }
              }
              this.errorWorkList = this.$deepCopy(errorWorkList)
              this.open = true
            })
          } else {
            console.log('休息')
            this.erroStatus = true
            this.$alert('当前时间，没有考勤异常无需补卡', '提示', {
              confirmButtonText: '确定',
              callback: action => {
              }
            });
            return
          }
        }
      } else {
        this.errorWorkList = []
        this.dayIndex = null
        this.erroStatus = false
      }
    },
    onSubmit(flowline) {
      if (this.erroStatus) {
        this.$message.error('当前时间，没有考勤异常无需补卡')
        return
      }
      if (!this.dayData || !this.timeData) {
        this.$message.error('补卡时间不能为空')
        return
      }
      if (!this.dayIndex) {
        this.$message.error('未找到需要补卡的班次')
        return
      }

      let query_ = JSON.parse(JSON.stringify(this.form))
      let that =this
      let examinelog_ = []
      for (let item of flowline) {
        let userData_ = []
        if (item.userData) {
          for (let user of item.userData) {
            userData_.push(user.id)
          }
        }
        examinelog_.push({
          // item.assignedType
          examineId: 0, // 审核id
          name: item.exaName, // 名称
          content: '', //
          userIds: userData_.join(','), //  步骤审核人
          isExamine: 0, //  0-待审核1-通过2-驳回
          type: item.moreUserSign ? (item.moreUserSign == 'AND' ? 1 : 2) : 0, // 全部用户审核，1个用户审核
          isAuto: item.assignedType == 'AUTO_PASS' ? 1 : 0, // 是否直接通过0否1是
          style: item.assignedType == 'CC' ? 2 : 1, // 1 审核 2 抄送
        })
      }
      query_.userId = this.userId
      query_.signTime = `${this.dayData} ${this.timeData}:00`
      query_.examineLog = examinelog_
      query_.flowId = this.flowData ? this.flowData.id : 0
      query_.type = this.dayIndex.type
      delete query_.isEmpty
      if(this.flagLoading){
        return
      }
      this.flagLoading = true
      this.$modal.loading("正在保存中，请稍候...");
      cardReplacementAdd(query_).then(res => {
        console.log('res===>', res)
        this.$message.success('提交成功')
        this.reset()
      })
      setTimeout(()=>{
        that.flagLoading = false
      }, 1000)
    },
    reset() {
      this.form = {
        userId: 0, // 用户id
        signTime: 0, // 补卡时间
        content: '', // 补卡原因
        file: '', // 文件地址
        flowId: 0, // 审核流程id
        isEmpty: '1'
      }
      this.dayData = ''
      this.timeData = ''
      this.erroStatus = false
      this.dayIndex = null // 补卡信息
      this.$emit('reset')
      this.$modal.closeLoading();
    },
  }
}
</script>

<style scoped>
.examineTitle {
  font-size: 20px;
  font-weight: bold;
}

.line {
  text-align: center;
}

.tips-rule {
  color: #999;
  font-size: 12px;
}

.tips-rule span {
  color: #2a99ff;
  cursor: pointer;
}

.not-error-line {
  color: #ed5565;
  font-size: 12px;
}

.card-list {
  padding: 0 10px;
}

.card-list p {
  cursor: pointer;
  padding: 10px;
  color: #000;
  margin: 0;
  border-radius: 3px;
}

.card-list p:hover {
  background: #f4f4f4;
}

.add-card-line {
  padding: 0 10px;
  font-size: 12px;
  color: #777;
}
</style>
